import React, { useEffect, useState, useRef } from 'react'
import { Table, Button, message, Modal, Switch } from 'antd'
import {
  DeleteOutlined,
  EditOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import axios from 'axios'
import UserFrom from '../../../components/user-manage/userFrom'
const { confirm } = Modal

export default function UserList() {
  const [dataSource, setdataSource] = useState([])
  const [roleList, setroleList] = useState([])
  const [regionList, setregionList] = useState([])
  const [isAddVisible, setisAddVisible] = useState(false)
  const [isUpdateVisible, setisUpdateVisible] = useState(false)
  const [isUpdateDisable, setisUpdateDisable] = useState(false)
  const [updataCurrent, setupdataCurrent] = useState({})
  const addFrom = useRef(null)
  const updateFrom = useRef(null)

  const { roleId, region, username } = JSON.parse(localStorage.getItem('token'))
  useEffect(() => {
    axios.get('/roles').then((res) => {
      // console.log('99955555', res.data);
      setroleList(res.data)
    })
  }, [])
  useEffect(() => {
    axios.get('/users?_expand=role').then((res) => {
      // console.log('999', res.data);
      let list = res.data
      setdataSource(
        roleId === 1
          ? list
          : [
              ...list.filter((item) => item.username === username),
              ...list.filter((item) => item.region === region && roleId === 3),
            ]
      )
    })
  }, [roleId, region, username])
  useEffect(() => {
    axios.get('/regions').then((res) => {
      // console.log('999', res.data);
      setregionList(res.data)
    })
  }, [])
  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      key: 'region',
      filters:
        roleId === 1
          ? [
              {
                text: '全球',
                value: '全球',
              },
              ...regionList.map((item) => ({
                text: item.title,
                value: item.value,
              })),
            ]
          : '',
      onFilter: (value, item) => {
        if (value === '全球') {
          return item.region === ''
        }
        return item.region === value
      },
      render: (region) => {
        return <b>{region === '' ? '全球' : region}</b>
      },
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      render: (role) => {
        return role?.roleName
      },
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '用户状态',
      key: 'roleState',
      render: (item) => {
        return (
          <Switch
            checked={item.roleState}
            onChange={() => roleStateChange(item)}
            disabled={item.default}
          ></Switch>
        )
      },
    },
    {
      title: '操作',
      render: (item) => {
        return (
          <div>
            <Button
              type="primary"
              onClick={() => removeConfim(item)}
              danger
              disabled={item.default}
              shape="circle"
              icon={<DeleteOutlined />}
            />
            <Button
              type="primary"
              shape="circle"
              onClick={() => clickUpdate(item)}
              disabled={item.default}
              icon={<EditOutlined />}
            />
          </div>
        )
      },
    },
  ]
  // 删除事件二次确认
  const removeConfim = (item) => {
    confirm({
      title: '您确定要删除吗?',
      icon: <ExclamationCircleOutlined />,
      cancelText: '取消',
      onOk() {
        removeMethed(item)
      },
      onCancel() {},
    })
  }
  // 删除的函数
  const removeMethed = (item) => {
    // console.log('33', item);
    setdataSource(dataSource.filter((data) => data.id !== item.id))
    axios.delete(`/users/${item.id}`).then((res) => {
      if (res.status === 200) {
        message.success('删除成功')
      }
    })
  }
  // 添加用户确认按钮事件
  const addFromOk = () => {
    addFrom.current
      .validateFields()
      .then((value) => {
        const query = {
          ...value,
          default: false,
          roleState: true,
        }
        addFrom.current.resetFields()
        setisAddVisible(false)
        // 先添加到后端设置id，在改变前段
        axios.post('/users', query).then((res) => {
          if (res.status === 201) {
            message.success('添加成功')
            setdataSource([
              ...dataSource,
              {
                ...res.data,
                role: roleList.filter((item) => item.id === value.roleId)[0],
              },
            ])
          }
        })
      })
      .catch(() => {
        message.success('添加失败')
      })
  }
  // 修改用户状态
  const roleStateChange = (item) => {
    item.roleState = !item.roleState
    setdataSource([...dataSource])
    axios.patch(`/users/${item.id}`, {
      roleState: item.roleState,
    })
  }
  // 打开更新用户模态框
  const clickUpdate = async (item) => {
    await setisUpdateVisible(true)
    await updateFrom.current.setFieldsValue(item)
    await setupdataCurrent(item)
    if (item.roleId === 1) {
      setisUpdateDisable(true)
    } else {
      setisUpdateDisable(false)
    }
  }
  // 更新用户
  const updateFromOk = () => {
    updateFrom.current.validateFields().then((value) => {
      setisUpdateVisible(false)
      setdataSource(
        dataSource.map((item) => {
          if (item.id === updataCurrent.id) {
            return {
              ...item,
              ...value,
              role: roleList.filter((item) => item.id === value.roleId)[0],
            }
          }
          return item
        })
      )
      setisUpdateDisable(!isUpdateDisable)

      axios.patch(`/users/${updataCurrent.id}`, value).then((res) => {
        // console.log(res);
        if (res.status === 200) {
          message.success('更改成功')
        }
      })
    })
  }

  return (
    <div>
      <Button
        type="primary"
        onClick={() => setisAddVisible(true)}
        shape="round"
        icon={<PlusOutlined />}
      >
        添加用户
      </Button>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          pageSize: 10,
        }}
        rowKey={(item) => item.id}
      ></Table>

      <Modal
        visible={isAddVisible}
        title="添加用户"
        okText="确定"
        cancelText="取消"
        closable={false}
        maskClosable={false}
        onCancel={() => {
          addFrom.current.resetFields()
          setisAddVisible(false)
        }}
        onOk={addFromOk}
      >
        <UserFrom
          regionList={regionList}
          roleList={roleList}
          ref={addFrom}
        ></UserFrom>
      </Modal>

      <Modal
        visible={isUpdateVisible}
        title="更新用户"
        okText="更新"
        cancelText="取消"
        closable={false}
        maskClosable={false}
        onCancel={() => {
          setisUpdateVisible(false)
          setisUpdateDisable(!isUpdateDisable)
        }}
        onOk={updateFromOk}
      >
        <UserFrom
          isUpdate={true}
          ref={updateFrom}
          regionList={regionList}
          roleList={roleList}
          isUpdateDisable={isUpdateDisable}
        ></UserFrom>
      </Modal>
    </div>
  )
}
